package com.cxz.kotlin.baselibs.utils;

import android.app.Activity;

import com.cxz.kotlin.baselibs.utils.typeadapter.DefaultDoubleAdapter;
import com.cxz.kotlin.baselibs.utils.typeadapter.DefaultFloatAdapter;
import com.cxz.kotlin.baselibs.utils.typeadapter.DefaultIntegerAdapter;
import com.cxz.kotlin.baselibs.utils.typeadapter.DefaultLongAdapter;
import com.cxz.kotlin.baselibs.utils.typeadapter.StringTypeAdapter;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.Multipart;

/**
 * Gson解析工具类
 * Created by Czg on 2016/8/3.
 */
public class GsonHelper {

    private static Gson instance;

    private GsonHelper() {
    }

    public static Gson getInstance() {
        if (instance == null) {
            instance = buildGson();
        }
        return instance;
    }

    private static Gson buildGson() {
        return new GsonBuilder()
                //如果不设置serializeNulls,序列化时默认忽略NULL
                .serializeNulls()
                //使打印的json字符串更美观，如果不设置，打印出来的字符串不分行
                .setPrettyPrinting()
                //自定义类型适配器
                .registerTypeAdapter(Double.class, new DefaultDoubleAdapter())
                .registerTypeAdapter(Float.class, new DefaultFloatAdapter())
                .registerTypeAdapter(Integer.class, new DefaultIntegerAdapter())
                .registerTypeAdapter(Long.class, new DefaultLongAdapter())
                .registerTypeAdapter(String.class, new StringTypeAdapter())
                .create();
    }

    /**
     * 解析一个Object
     *
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T parse(String json, Class<T> type) {
        if (json == null || "".equals(json)) {
            return null;
        }
        try {
            if (type == String.class) {
                return (T) json;
            }
            return getInstance().fromJson(json, type);
        } catch (Exception e) {
            LogUtil.e("mgc_gson_parse_exception", e.toString());
            return null;
        }
    }

    /**
     * 解析一个Array
     *
     * @param json
     * @param <T>
     * @return
     */
    public static <T> ArrayList<T> parseArray(String json, Class<T> cls) {
        ArrayList<T> mList = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            mList.add(getInstance().fromJson(elem, cls));
        }
        return mList;
    }


    /**
     * 实体类转换成Json字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        return getInstance().toJson(object);
    }

    public static String toSingleParmerJson(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(key, value);
        } catch (Exception e) {

        }
        return jsonObject.toString();
    }

    public static RequestBody getRequestBoby(HashMap<String, String> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
    }

    public static RequestBody getRequestIntBoby(HashMap<String, Integer> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
    }

    public static RequestBody getRequestObjectBoby(HashMap<String, Object> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
    }

    public static RequestBody getRequestBoby(ArrayList<String> key, ArrayList<Object> value) {
        HashMap<String, Object> map = new HashMap<>();
        for (int i = 0; i < key.size(); i++) {
            map.put(key.get(i), value.get(i));
        }
        LogUtil.d("map->" + toJson(map));
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
    }

    public static HashMap<String, RequestBody> getRequestBodyMap(ArrayList<String> key, ArrayList<String> value) {
        HashMap map = new HashMap<String, RequestBody>();
        for (int i = 0; i < key.size(); i++) {
            map.put(key.get(i), RequestBody.create(null, value.get(i)));
        }
        return map;

    }

    public static MultipartBody getMutiPartBody(String filepath, String Filekey) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), new File(filepath));
        builder.addFormDataPart(Filekey, filepath, requestBody);

        builder.setType(MultipartBody.FORM);

        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }


    public static MultipartBody.Part uploadSinglePart(String filepath, String Filekey) {

        File file = new File(filepath);
        // 创建 RequestBody，用于封装构建RequestBody
        // RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);

        // MultipartBody.Part  和后端约定好Key，这里的partName是用file
        MultipartBody.Part body = MultipartBody.Part.createFormData(Filekey, file.getName(), requestFile);
        return body;
    }


    public static ArrayList<MultipartBody.Part> uploadPics(ArrayList<String> filepaths, String Filekey) {

        ArrayList parts = new ArrayList<MultipartBody.Part>();
        for (String filepath:filepaths) {
            File file = new File(filepath);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData(Filekey, file.getName(), requestFile);
            parts.add(body);
        }
        return parts;
    }

    /**
     * Object 字段要用@Expose 注解
     *
     * @param object 序列化对象
     * @param skips  要屏蔽的字段
     * @return
     */
    public static String toJsonSkip(Object object, final String[] skips) {
        Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                if (skips == null) {
                    return false;
                }
                for (String s : skips) {
                    if (s.equals(f.getName())) {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        }).create();
        return gson.toJson(object);
    }

    /**
     * 根据文件名获取本地数据
     *
     * @param fileName 文件名
     * @return 实体对象
     */
    public static <T> T getFileData(Activity activity, String fileName, Class<T> type) {
        try {
            InputStreamReader inputStreamReader =
                    new InputStreamReader(activity.getAssets().open(fileName));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = "";
            String result = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            if (type == String.class) {
                return (T) result;
            }
            return getInstance().fromJson(result, type);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}
